<script name="CartSku" setup lang="ts">
import { onClickOutside } from '@vueuse/core'
import { onMounted, ref, defineEmits } from 'vue'
import GoodsSku from '@/views/goods/components/goods-sku.vue'
import { apiRes, GoodsInfo, Sku } from '@/types/data'
import request from '@/utils/request'
import Message from '@/components/message'

const props = defineProps({
  attrsText: {
    type: String,
    default: '',
  },
  skuId: {
    type: String,
    default: '',
  },
})

const visible = ref(false)
const toggle = () => {
  visible.value = !visible.value
}
const target = ref(null)
onClickOutside(target, () => {
  visible.value = false
})

// 获取商品信息
const goods = ref({} as GoodsInfo)
onMounted(async () => {
  const res = await request.get<apiRes<GoodsInfo>>(`/goods/sku/${props.skuId}`)
  goods.value = res.data.result
})

// 修改规格
let currentSkuId = ''
const changeSku = (skuId: string) => {
  currentSkuId = skuId
  //   console.log('变化了', currentSkuId)
}

const emit = defineEmits<{
  (e: 'change', sku: Sku): void
}>()

const submit = () => {
  // 1.判断是否修改了商品的规格，并且和老规格不一样
  //   console.log(currentSkuId)
  if (currentSkuId && currentSkuId !== props.skuId) {
    const sku = goods.value.skus.find((item) => item.id === currentSkuId)
    //   2.传给父组件 cart/index
    emit('change', sku as Sku)
    // 3.关闭规格组件
    visible.value = false
  } else {
    Message.warning('请先修改规格或完善规格信息')
  }
}
</script>

<template>
  <div class="cart-sku" ref="target">
    <div class="attrs" @click="toggle">
      <span class="ellipsis">{{ attrsText }}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="layer" v-if="visible">
      <GoodsSku
        :goods="goods"
        :skuId="skuId"
        @change-sku="changeSku"
      ></GoodsSku>
      <XtxButton
        type="primary"
        size="mini"
        style="margin-left: 60px"
        @click="submit"
      >
        确认
      </XtxButton>
    </div>
  </div>
</template>

<style scoped lang="less">
.cart-sku {
  height: 28px;
  border: 1px solid #f5f5f5;
  padding: 0 6px;
  position: relative;
  margin-top: 10px;
  display: inline-block;
  .attrs {
    line-height: 24px;
    display: flex;
    span {
      max-width: 230px;
      font-size: 14px;
      color: #999;
    }
    i {
      margin-left: 5px;
      font-size: 14px;
    }
  }
  .layer {
    position: absolute;
    left: -1px;
    top: 40px;
    z-index: 10;
    width: 400px;
    border: 1px solid @xtxColor;
    box-shadow: 2px 2px 4px lighten(@xtxColor, 50%);
    background: #fff;
    border-radius: 4px;
    font-size: 14px;
    padding: 20px;
    &::before {
      content: '';
      width: 12px;
      height: 12px;
      border-left: 1px solid @xtxColor;
      border-top: 1px solid @xtxColor;
      position: absolute;
      left: 12px;
      top: -8px;
      background: #fff;
      transform: scale(0.8, 1) rotate(45deg);
    }
  }
}
</style>
